import { initUser } from './user.js';
import { getContext } from './context.js';

export async function analyzeFilePurpose(pdfFile, zipFileHash) {
    const context = getContext();
    context.uploadStatus = '正在分析文件用途：' + pdfFile.fileName;
    if (pdfFile.purpose) {
        return;
    }
    const imageList = pdfFile.imageList;
    const pdfFileHash = pdfFile.hash;
    let firstImage = imageList.find((image) =>
        image.imageName.includes('_page_1.')
    );
    if (!firstImage) {
        if (imageList.length === 1) {
            firstImage = imageList[0];
        }
    }
    if (!firstImage) {
        context.uploadStatus = '没找到图片，无法分析文件用途';
        throw new Error('没找到首张图片，文件用途分析失败');
    }
    const uuid = await initUser();
    const url = '/analyze-file-purpose';
    const formData = new FormData();
    formData.append('uuid', uuid);
    formData.append('zipFileHash', zipFileHash);
    formData.append('pdfFileHash', pdfFileHash);
    formData.append('imageFileName', firstImage.imageName);
    const response = await fetch(url, {
        method: 'post',
        body: formData,
    });
    console.log('response: ', response);
    const json = await response.json();
    console.log('json: ', json);
    if (json.code == 200) {
        pdfFile.purpose = json.result;
        return;
    }
    if (json.code === 500) {
        context.uploadStatus = '服务器错误：' + json.message;
        return;
    }
    throw new Error('请求服务器分析文件用途失败');
}
